<?php
/**
 * By   :    Ernest Dey
 * Date :    4/21/12
 * Time :    1:23 PM
 * File :    User.php
 */
require_once 'Database.php';

class User extends Database
{
    private $table = 'users';
    private $role;

    public function login($data)
    {
        if (is_array($data)) {
            $found = parent::authenticate($data);
            if (is_object($found) && $found->role == 'student') {
                $this->redirect('student/test.php');
            } elseif (is_object($found) && ($found->role == 'admin' || $found->role == 'counselor')) {
                $this->redirect('dashboard.php');
            } else {
                return $found;
            }
        } else {
            return false;
        }
    }

    public function save($data)
    {
        if ($this->compare($data['password'], $data['confirmpassword'])) {
            $data['password'] = sha1($data['password']);
            $data['confirmpassword'] = sha1($data['confirmpassword']);

            $result = $this->insert($this->table, $data);

            if (isset($result['type']) && $result['type'] == 'msg_ok') {
                Session::set('uid', $result['uid']);
                Session::set('uname', $result['uid']);
                Session::set('role', $result['uid']);
                $this->redirect('student/wizard.php');
            } else {
                return $result;
            }


            return $this->insert($this->table, $data);
        } else {
            return '<b>Password mismatch</b>';
        }

    }

    private function compare($pas1, $pas2) {
        return $pas1 === $pas2 ? true : false;
    }

}

class Counselor extends Database
{


    private $table = 'users';

    public function save($data)
    {
        return $this->insert($this->table, $data);
    }

    public function find($arguments = false, $table = null)
    {
        $this->table = !is_null($table) ? $table : $this->table;
        return parent::find($this->table, $arguments);
    }


    public function update($data)
    {
        if (isset($data['id'])) {
            $id = $data['id'];
            unset($data['id']);
            return parent::update($this->table, $id, $data);
        }
    }

    public function delete($id)
    {
        if ($id) {
            return parent::delete($id, $this->table);
        }
    }

}
